package com.ruoyi.web.controller.greatWall;

import java.io.File;
import java.util.List;
import java.util.Map;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.config.FileUploadProper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.CateNameEnum;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.PqlUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.config.ExceptionThrower;
import com.ruoyi.framework.enums.ErrorInfo;
import com.ruoyi.system.domain.greatWall.CollectionEntity;
import com.ruoyi.system.domain.greatWall.GwRelic;
import com.ruoyi.system.domain.greatWall.Pql;
import com.ruoyi.system.domain.greatWall.Years;
import com.ruoyi.system.mapper.greatWall.RelicStatisticsMapper;
import com.ruoyi.system.mapper.greatWall.YearsMapper;
import com.ruoyi.system.service.CollectionService;
import com.ruoyi.system.service.CommonInter;
import com.ruoyi.system.service.SysDepartService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.common.core.controller.BaseController;


import com.ruoyi.system.service.IGwRelicService;

import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 长城三维文物Controller
 * 
 * @author ruoyi
 * @date 2023-04-23
 */
@RestController
@RequestMapping("/gwRelic")
public class GwRelicController extends BaseController
{
    @Resource
    private IGwRelicService gwRelicService;

    @Resource
    private YearsMapper yearsMapper;

    @Resource
    private SysDepartService departService;

    @Resource
    private CollectionService collectionService;

    @Resource
    private RelicStatisticsMapper statisticsMapper;

    @Autowired
    private FileUploadProper fileUploadProperties;

    @Resource
    private CommonInter commonInter;




    /**
     * 添加/编辑 二维(三维)数据
     */
    @PutMapping
    public GwRelic save(@RequestBody GwRelic relic){
        QueryWrapper<GwRelic> wrapper=new QueryWrapper<>();

        //判断部门是否存在
        LoginUser user = SecurityUtils.getCurrentUser();
        if (StringUtils.isEmpty(relic.getDepId())){
            relic.setDepId(String.valueOf(user.getDeptId()));
            wrapper.eq("dep_id",user.getDeptId());
        }else {
            wrapper.eq("dep_id",relic.getDepId());
        }
        List<Object> list;

        wrapper.eq("name",relic.getName());
        wrapper.eq("diff_status",relic.getDiffStatus());

        /*
         * 查询文物名称是否重复,很重要的是根据馆藏单位和部门查询
         * 尤其是馆藏单位,因为一个部门下可能有多个馆藏单位.馆藏单位之间的文物有可能名称会重复
         * typeId:馆藏单位
         * dep_id:部门
         */
        wrapper.eq("type_id",relic.getTypeId());
        if(StringUtils.isNotEmpty(relic.getCreateDate())){
            relic.setUpdateDate(DateUtil.getNowTime());
        }else {
            //获取当前时间
            relic.setCreateDate(DateUtil.getNowTime());
        }

        if (StringUtils.isNotEmpty(relic.getId())){
            wrapper.ne("id",relic.getId());
            list= gwRelicService.listObjs(wrapper);
        }else {
            list=gwRelicService.listObjs(wrapper);
        }
        boolean b = commonInter.existName(relic, wrapper);

        System.out.println("是否存在:"+ b);

        boolean flag = list.size() ==0;
        if (flag){
            gwRelicService.saveOrUpdate(relic);
        }else {
            ExceptionThrower.of(ErrorInfo.TITLE_EXIST);
        }
        return relic;
    }




    /**
     * 查询长城三维文物列表
     */
    @PreAuthorize("@ss.hasPermi('system:relic:list')")
    @GetMapping("/list")
    public TableDataInfo list(GwRelic gwRelic)
    {
        startPage();
        List<GwRelic> list = gwRelicService.selectGwRelicList(gwRelic);
        return getDataTable(list);
    }

    /**
     * 根据id删除
     */
    @DeleteMapping(value = "/{id}")
    public void delete(@PathVariable String id){
        gwRelicService.removeById(id);
    }

    /**
     *根据id查询
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getById(@PathVariable String id){
        GwRelic relic = gwRelicService.getById(id);
        String depName = departService.getNameById(relic.getDepId());
        relic.setDepName(depName);
        String diffStatusName=relic.getDiffStatus() == 1 ? "二维" : "三维";
        relic.setDiffStatusName(diffStatusName);

        String pqlName="1".equals(relic.getPql()) ? "精美" : "普通";
        relic.setPqlName(pqlName);

        //年代
        if (StringUtils.isNoneEmpty(relic.getYearsId())){
            Years years=yearsMapper.selectById(relic.getYearsId());
            if (years !=null){
                relic.setYearName(years.getName());
            }
        }
        //材质
        String type="material";
        if (StringUtils.isNotEmpty(relic.getMaterialId())){
            String cateName = statisticsMapper.getByMaterialId(relic.getMaterialId(),type);
            relic.setMaterialName(cateName);
        }

        String cateName = CateNameEnum.getName(relic.getCategoryId());
        relic.setCategoryName(cateName);

        return success(relic);
    }

    @GetMapping(value = "/materialList")
    public List<Map<String,String>> mapList(){
        return PqlUtil.list();
    }

    @GetMapping(value = "/review/{id}/{status}")
    public void status(@PathVariable String id,@PathVariable Integer status){
        gwRelicService.setStatus(id,status);
    }


    @GetMapping(value = "recommend")
    public Page<GwRelic> recommendList(Page<GwRelic> page,GwRelic relic){
        return gwRelicService.recommonList(page,relic);
    }


    //三维根据名称查询二维详情
    @GetMapping(value = "/detail")
    public GwRelic detail(GwRelic gwRelic){
        QueryWrapper<GwRelic> wrapper=new QueryWrapper<>();
        if (gwRelic !=null){
            if (StringUtils.isNotEmpty(gwRelic.getName())){
                wrapper.eq("name",gwRelic.getName());
            }
            if(StringUtils.isNotEmpty(gwRelic.getId())){
                wrapper.eq("id",gwRelic.getId());
            }

            /*
             * 部门id和馆藏单位id尤为重要
             */
            if(StringUtils.isNotEmpty(gwRelic.getDepId())){
                wrapper.eq("dep_id",gwRelic.getDepId());
            }

            if(StringUtils.isNotEmpty(gwRelic.getTypeId())){
                wrapper.eq("type_id",gwRelic.getTypeId());
            }

            Integer diffStatus=gwRelic.getDiffStatus() ==null ? 1 : gwRelic.getDiffStatus();
            wrapper.eq("diff_status",diffStatus);
        }
        GwRelic relic = gwRelicService.getOne(wrapper);
        if (relic !=null){
            String depName = departService.getNameById(relic.getDepId());
            relic.setDepName(depName);
        }

        assert relic != null;
        if(relic.getDiffStatus() !=null){
            String diffStatusName=relic.getDiffStatus() == 1 ? "二维" : "三维";
            relic.setDiffStatusName(diffStatusName);
            String pqlName=relic.getDiffStatus() == 1 ? "精美" : "普通";
            relic.setPqlName(pqlName);
        }

        //判断压缩包是否存在
        if (StringUtils.isNotEmpty(relic.getZipUrl())){
            String filePath=relic.getZipUrl();
            filePath=fileUploadProperties.getMappingPath()+"/msm-admin/"+filePath.replace("/data/","").replace("index.html","marmoset.js");
            System.out.println("响应的数据:"+filePath);
            File file=new File(filePath);

            boolean exists = file.exists();
            if (exists){
                relic.setExistsZipUrl(1);
            }else {
                relic.setExistsZipUrl(2);
            }
        }

        //年代
        if (StringUtils.isNoneEmpty(relic.getYearsId())){
            Years years=yearsMapper.selectById(relic.getYearsId());
            if (years !=null){
                relic.setYearName(years.getName());
            }
        }
        //材质
        String type="material";
        if (StringUtils.isNotEmpty(relic.getMaterialId())){
            String cateName = statisticsMapper.getByMaterialId(relic.getMaterialId(),type);
            relic.setMaterialName(cateName);
        }

        String cateName = CateNameEnum.getName(relic.getCategoryId());
        relic.setCategoryName(cateName);

        //馆藏单位名称
        if (StringUtils.isNotEmpty(relic.getTypeId())){
            CollectionEntity entity = collectionService.getById(relic.getTypeId());
            if (entity !=null) {
                relic.setCollectionName(entity.getName());
            }
        }
        return relic;

    }

    //精美 & 普通
    @GetMapping(value = "pqlList")
    public AjaxResult list(){
        return success(Pql.pqlList());
    }


    @GetMapping("/info")
    public AjaxResult relicInfo() {
        return success(gwRelicService.getInfo());
    }



    }
